// Token 管理工具
import { createRequest } from '@/config/network.js'

/**
 * 检查 token 是否即将过期（提前5分钟刷新）
 */
export const isTokenExpiringSoon = (token) => {
  if (!token) return true;
  
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    const exp = payload.exp * 1000; // 转换为毫秒
    const now = Date.now();
    const fiveMinutes = 5 * 60 * 1000; // 5分钟
    
    return (exp - now) < fiveMinutes;
  } catch (e) {
    console.error('解析token失败:', e);
    return true;
  }
};

/**
 * 刷新 token
 */
export const refreshToken = async () => {
  try {
    const refreshToken = uni.getStorageSync('refreshToken');
    if (!refreshToken) {
      throw new Error('没有刷新token');
    }

    const response = await createRequest({
      url: '/auth/refresh',
      method: 'POST',
      data: { refreshToken }
    });

    if (response.statusCode === 200 && response.data.success) {
      const { accessToken, refreshToken: newRefreshToken } = response.data;
      
      // 更新存储的token
      uni.setStorageSync('accessToken', accessToken);
      if (newRefreshToken) {
        uni.setStorageSync('refreshToken', newRefreshToken);
      }
      
      console.log('Token刷新成功');
      return accessToken;
    } else {
      throw new Error('Token刷新失败');
    }
  } catch (error) {
    console.error('Token刷新失败:', error);
    // 清除无效的token
    uni.removeStorageSync('accessToken');
    uni.removeStorageSync('refreshToken');
    throw error;
  }
};

/**
 * 获取有效的 access token（自动刷新）
 */
export const getValidAccessToken = async () => {
  let token = uni.getStorageSync('accessToken');
  
  if (!token) {
    throw new Error('没有访问token');
  }
  
  // 检查是否需要刷新
  if (isTokenExpiringSoon(token)) {
    console.log('Token即将过期，开始刷新...');
    try {
      token = await refreshToken();
    } catch (error) {
      console.error('Token刷新失败，需要重新登录:', error);
      // 跳转到登录页面
      uni.reLaunch({
        url: '/pages/login/index'
      });
      throw error;
    }
  }
  
  return token;
};

/**
 * 处理401错误（token过期）
 */
export const handleTokenExpired = async (originalRequest) => {
  try {
    console.log('检测到401错误，尝试刷新token...');
    const newToken = await refreshToken();
    
    // 重新发送原始请求
    if (originalRequest.header) {
      originalRequest.header['Access-Token'] = `Bearer ${newToken}`;
    }
    
    return await uni.request(originalRequest);
  } catch (error) {
    console.error('Token刷新失败，跳转到登录页面:', error);
    uni.reLaunch({
      url: '/pages/login/index'
    });
    throw error;
  }
};

